/**
 * 路由鉴权
 */
import {
	getCookieValue
} from '~/util/index.js';
import aes from '~/util/aes.js'

export default function ({
	route,
	req,
	res,
	redirect,
	app
}) {
	let isServer = process.server;
	let isClient = process.client;
	let redirectURL = '/';//默认跳转到后台管理的登录页
	let token, path, path2; //path是路由地址，path2是路由地址加query的全路径
	//在服务器端
	if (isServer) {
		let cookies = req.headers.cookie;
		token = getCookieValue('token', cookies);
		path = req.url.split('?')[0];
		path2 = req.originalUrl; //req.originalUrl是全路径，带query
	}
	//在客户端
	if (isClient) {
		token = app.$cookies.get('token');
		path = route.path;
		path2 = escape(route.fullPath);
	}
	/**
	 * TODO：①一级鉴权：判断是否已登录
	 * TIPS：采用白名单策略（不在数组中即需要验证是否登录，没登录跳转到登录页）
	 * 判断路由得判断不带query的那一部分路径(例如/index，即上述的path)，跳转到登录页时得告诉登录页跳转过来的路由全路径(例如/index?a=1，即上述的path2)
	 * ADDITIONAL:登录，注册的路由是判断是否登录时最起码要过滤的路由页面。
	 */

	// "/payment",
	// '/payment/payForm',
	// '/payment/shopping',
	let routeArr = [
		"/",
		"/user/apply",
		"/login",
		"/register",
		"/admin/login",
		"/admin/register",
		"/admin/prelogin",
		"/admin/agentCenter",
		"/ieTips",
		"/order/login",
		"/agentRegister",
		"/agentImprove",
		"/register",
		"/agentRegister",
		"/companyRegister",
		"/forgotPassword",
		'/companyLogin',
		'/QA',
		'/survey',
		'/activity',
		"/payment",
		'/payment/payForm',
		'/payment/patentPay',
		'/payment/vipPay',
		'/payment/rechargePay',
		'/payment/shopping'
	];
	//1.前台管理和后台管理的登录判断（前台管理和后台管理）
	if (routeArr.indexOf(path) == -1) {
		if (!token) {
			//如果路径是前台管理的路由之一
			// let userRouteArr = [
			// 	"/user",
			// 	// "/user/home", 将user/home添加到白名单,从转化平台过来的用户直接进入这个页面验证 0719
			// 	'/user/rank',
			// 	'/user/vip',
			// 	'/user/achievement',
			// 	"/user/home/menu",
			// 	// "/agent/home/menu",
			// 	'/user/news/notice',
			// 	'/user/payOrInvoice/purse',
			// 	'/user/news/communication',
			// 	'/user/order/patent',
			// 	'/user/order/software',
			// 	'/user/order/brand',
			// 	'/user/order/externalOrder',
			// 	'/user/myPay/payInquiry',
			// 	'/user/myPay/invoiceQuery',
			// 	'/user/myPay/invoiced',
			// 	'/user/order/fileDownload',
			// 	'/user/home/feedBack',
			// 	'/user/home/bankCard',
			// 	'/user/home/address',
			// 	'/user/home/recommend',
			// 	'/user/home/editPhone',
			// 	'/user/home/editPassword',
			// 	'/user/home/editInformation',
			// 	'/user/home/pointsTips',
			// 	'/user/home/levelRule',
			// 	"/user/myNews",

			// 	"/user/resetPw",
			// 	"/user/updatePwd",
			// 	"/user/updateTel",
			// 	"/user/verifyPhone",
			// 	"/user/home/editInformation",
			// 	'/user/personalCenter/myPurse',
			// 	'/user/personalCenter/dstribution',
			// 	'/user/myVIP',
			// 	'/user/payOrInvoice/payInfo',
			// 	'/user/order/allOrder',
			// 	'/user/order/allOrder',
			// ];
			// if (userRouteArr.indexOf(path) >= 0) {
			// 	redirectURL = '/'//跳转到前台管理的登录页面
			// }
			// //跳到登录页 
			// redirect(redirectURL + 'login?type=2' + '&routerfrom=' + path2)


			if(path.substr(0,5)=='/user'){
        redirect(redirectURL + 'login?type=2' + `&routerfrom=${path2}`)
			} else if(path.substr(0,6)=='/agent'){
				redirect(redirectURL + 'login?type=1' + `&routerfrom=${path2}`)
			} else if (path == '/activity/yearEnd') {
				redirect(redirectURL + 'login?type=2' + `&routerfrom=${path2}`)
			}
		} else {
			/**
			 * TODO：②二级鉴权：判断是否有权限访问此路由（前台管理和后台管理）
			 * TIPS：根据用户的角色判断，用户的所有信息和登录凭证（token）一样，也存储在cookie中
			 * 没有权限访问此路由时跳转到首页
			 */
			let user = isServer ? getCookieValue('cookiesUser', req.headers.cookie) : app.$cookies.get('cookiesUser');
			if (user) {
				user = JSON.parse(aes.Decrypt(user));
				if (isNull(user.role_id)) {
					if (path.indexOf('agentImprove') > -1) {
						return
					} else {
						//user信息异常
						redirect(redirectURL + 'login?type=2' + '&routerfrom=' + path2)
					}
				} else {
					/**
					 * 前台管理的路由只有普通用户（role_id为5）才能进，后台管理的路由反之。
					 * 2种用户账户不可僭越访问所述前台/后台管理的路由
					 */
					let routeArr3 = [
						'/survey',
						"/user",
						"/user/home",
						'/user/rank',
						'/user/vip',
						'/user/vip/newVIP',
						'/user/vip/presell',
						'/user/vip/pointsMall',
						'/user/achievement',
						"/user/home/menu",
						'/user/payOrInvoice/purse',
						'/user/news/notice',
						'/user/news/communication',
						'/user/order/patent',
						'/user/order/software',
						'/user/order/externalOrder',
						'/user/order/brand',
						'/user/myPay/payInquiry',
						'/user/myPay/invoiced',
						'/user/myPay/invoiceQuery',
						'/user/order/fileDownload',
						'/user/home/recommend',
						'/user/home/bankCard',
						'/user/home/address',
						'/user/home/editPhone',
						'/user/home/editPassword',
						'/user/home/editInformation',
						'/user/home/pointsTips',
						'/user/home/levelRule',
						'/user/home/feedBack',
						"/user/invoices",
						'/user/invoice/canBeInvoice',
						'/user/invoice/alreadyInvoice',
						"/user/myOrder",
						"/user/myNews",
						"/user/set/resetPw",
						"/user/set/updatePwd",
						"/user/set/updateTel",
						"/user/set/userData",
						"/user/home/editPhone",
						'/user/personalCenter/myPurse',
						'/user/personalCenter/dstribution',
						'/user/myVIP',
						'/user/payOrInvoice/payInfo',
						'/user/order/allOrder',
						"/payment",
						'/payment/payForm',
						'/activity/vipRaffle',
						'/activity/yearEnd'
					]
					//前台管理权限判断
					if (user.role_id == 5) {
						if (routeArr3.indexOf(path) == -1) {//不存在，即不属于此路由数组
							redirectURL = '/'
							//跳到登录页
							// redirect(redirectURL + '?from=' + path2)
							// 修改跳转到登录页路径，如果从外部链接过来，前往注册页面20200713
							redirect(redirectURL + 'user/home/menu')
						}
						//后台管理权限判断
					}else if(user.role_id==2){

						// '/agent/order/waitingAccepting',
						// '/agent/order/myOrder',
						// '/agent/settlement/purse',
						let routeArr4=[
							'/agent',
							'/activity/selection',
							'/agent/home/bankCard',
							'/agent/home/editInformation',
							'/agent/home/editPassword',
							'/agent/home/feedBack',
							'/agent/home/menu',
							'/agent/home/recommend',
							'/agent/news/communication',
							'/agent/news/notice',
							'/agent/order/myOrder',
							'/agent/order/waitingAccepting',
							'/agent/settlement/earnings',
							'/agent/settlement/purse',
							'/agent/achievement',
							"/agent/home",
							'/agent/rank',
							'/agent/vip',
							'/agent/vip/newVIP',
							'/admin/agentImprove',
							'/payment',
							'/payment/payForm',
						]
						if(routeArr4.indexOf(path) == -1){
							redirectURL = '/'
							redirect(redirectURL + 'agent/home/menu')
						}
					} else if (user.role_id == 10) {
						
					} else {
						if (routeArr3.indexOf(path) > 0) {

							redirectURL = '/admin/login'
							//跳到登录页
							redirect(redirectURL + '?from=' + path2)
						}
					}
				}
			} else {
				//user信息丢失
				redirect(redirectURL + 'login?type=2' + '&routerfrom=' + path2)
			}
		}
		//2.否则就是预注册管理的登录判断（预注册管理）
	} else {
		let agent = isServer ? getCookieValue('agent', req.headers.cookie) : app.$cookies.get('agent');
		let routeArr2 = ["/admin/agentCenter"];
		if (routeArr2.indexOf(path) >= 0) {
			if (!agent) {
				//跳到登录页
				// redirectURL = '/admin/prelogin';
				// redirectURL = '/login?type=1';
				redirect(redirectURL + 'login?type=1' + '&routerfrom=' + path2)
			}
		}
	}
}

function isNull(value) {
	if (value === null || value === '' || value === undefined) {
		return true;
	} else {
		return false
	}
}
